package com.flitsneak.rabbit.producer;

import com.flitsneak.common.entity.Info;
import com.flitsneak.common.entity.Messages;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.UUID;

/**
 * @author flitsneak
 * @email flitsneak@gmail.com
 * @date 2022/8/10 14:31
 * @description
 */
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/rabbit")
public class RabbitProducer {

    /**
     * ConfirmCallback
     * spring.rabbitmq.publisher-confirms=true
     * 在创建connectionFactory的时候设置PublisherConfirms(true)选项，开启confirmCallback
     * CorrelationData: 用来表示当前消息的唯一性。
     * 消息只要被broker接受到就会执行confirmCallback,如果是cluster模式，需要所有broker接受到才会调用	confirmCallback。
     * 被broker接收到只能表示message已经到达服务器，并不能保证消息一定会被投递到目标queue里，所以需要用到returnCallback。
     */

    private static final String TOPIC_EXCHANGE = "order-event-exchange";
    private static final String ORDER_CREATE = "order.create.order";

    private final RabbitTemplate rabbitTemplate;

    /**
     * 消息发送
     * @param num 发送数量
     */
    @GetMapping("/sendMessage/{num}")
    public String sendMessage(@PathVariable Integer num){
        for (int i = 0; i < num; i++) {
            if (i%2==0) {
                Messages messages = new Messages();
                messages.setTime(new Date());
                messages.setDes("hello!");
                messages.setId(66);
                rabbitTemplate.convertAndSend("hello-exchange", "hello.java", messages,new CorrelationData(UUID.randomUUID().toString()));
                log.info("消息发送成功{}", messages);
            }else {
                Info info = new Info();
                info.setTime(new Date());
                info.setDes("Many!");
                info.setId(88);
                rabbitTemplate.convertAndSend("hello-exchange", "hello.java", info);
                log.info("消息发送成功{}", info);
            }
        }
        return "ok";
    }

    /**
     * 延迟消息
     * @param num 发送数量
     */
    @GetMapping("/testDelay/{num}")
    public String testDelay(@PathVariable Integer num){
        for (int i = 0; i < num; i++) {
            Messages messages = new Messages();
            messages.setId(i);
            messages.setTime(new Date());
            messages.setDes("hello!");
            rabbitTemplate.convertAndSend(TOPIC_EXCHANGE,ORDER_CREATE, messages);
        }
        return "OK";
    }
}
